package com.study.jdbc.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

/**
* @Name: DBCPUtil
* @Description: DBCP数据源工具类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-19 上午10:05:55 
* @Version: V1.0
 */
public class DBCPUtil {
	
	private static DataSource dataSource ;
	private static final String PROPSPATH = "dbcpconfig.properties" ;
	
	static {
		ClassLoader loader = DBCPUtil.class.getClassLoader() ;
		InputStream in = loader.getResourceAsStream(PROPSPATH) ;
		Properties props = new Properties() ;
		try {
			props.load(in) ;
			dataSource = BasicDataSourceFactory.createDataSource(props) ;
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public static DataSource getDataSource() {
		return dataSource;
	}
	
	public synchronized static Connection getConnection() {
		Connection con = null ;
		try {
			con = dataSource.getConnection() ;
		} catch (Exception e) {
			e.printStackTrace() ;
		}
		return con ;
	}
	
	public static void close(Connection con, Statement s, ResultSet rs) {
		if(con != null) {
			try {
				con.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				con = null ;
			}
		}
		if(s != null) {
			try {
				s.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				s = null ;
			}
		}
		if(rs != null) {
			try {
				rs.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				rs = null ;
			}
		}
	}

	

}
